package com.pojoin.cms.util.criteria.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.pojoin.cms.util.criteria.Criteria;
import com.pojoin.cms.util.criteria.CriteriaInnerValue;

/**
 * @author haines
 * @date 2009.09.15
 * 键值对条件解释类
 */
public class CriteriaKeyValue implements Criteria {
	/**
	 * 键
	 */
	private String key;
	/**
	 * 操作符
	 */
	private String operator;
	/**
	 * 值
	 */
	private Object value;
	/**
	 * Or关系的子节点列表
	 */
	private List<Criteria> orList;
	/**
	 * And关系的兄弟节点
	 */
	private Criteria and;

	@Override
	public Criteria and(Criteria criteria) {
		this.and = criteria;
		return criteria;
	}

	@Override
	public String getSQLCriteria() {

		return "("+createSelfCriteriaValue()
		+ createAndCriteriaValue()
		+ createChildrenCriteriaValue() +")";
	}

	private String createAndCriteriaValue()
	{
		if (this.and != null)
		{
			return " and " +this.and.getSQLCriteria();
		}
		return "";
	}

	private String createChildrenCriteriaValue() {
		String cvalue = "";
		for (Criteria c : this.orList) {
			cvalue += " or " + c.getSQLCriteria();
		}
		return cvalue;
	}


	@Override
	public Criteria or(Criteria criteria) {
		this.orList.add(criteria);
		return this;
	}

	public CriteriaKeyValue(String key, String operator, Object value) {
		this.key = key;
		this.operator = operator;
		this.value = value;

		this.orList = new ArrayList<Criteria>();
	}

	public CriteriaKeyValue(String key, String operator) {
		this(key, operator, null);
	}
	
	public CriteriaKeyValue(String key) {
		this(key, null, null);
	}

	private String createSQLValue(Object cl)
	{
		if(cl.getClass() == CriteriaInnerValue.class)
		{
			return cl.toString();
		}
		if (cl.getClass() == String.class)
		{
			return "'"+cl+"'";
		}
		if (cl.getClass() == Date.class)
		{
			return "'"+cl+"'";
		}		
		return cl.toString();
	}

	private String createSelfCriteriaValue()
	{
		if(this.value != null)
		{
			return key+operator+createSQLValue(value);
		}
		else
		{
			if(this.operator !=null)
			{
				return key+operator;
			}else
			{
				return key;
			}
		}
	}

	public String getKey() {
		return key;
	}

	public String getOperator() {
		return operator;
	}

	public Object getValue() {
		return value;
	}

	public List<Criteria> getOrList() {
		return orList;
	}

	public Criteria getAnd() {
		return and;
	}

}
